package com.google.code.swingonfire.border;

import java.util.LinkedHashMap;

public class ShadowBorderCache extends LinkedHashMap<ShadowBorderCacheKey, ShadowBorderCacheEntry>
{

    private static final long serialVersionUID = -349747859622931302L;

    private static ShadowBorderCache instance = new ShadowBorderCache(8);

    public static ShadowBorderCache getInstance()
    {
        return instance;
    }

    public static void setCapacity(int capacity)
    {
        ShadowBorderCache.instance = new ShadowBorderCache(capacity);
    }

    private final int capacity;

    private ShadowBorderCache(int capacity)
    {
        super(capacity, 0.75f, true);

        this.capacity = capacity;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ShadowBorderCacheEntry get(Object key)
    {
        ShadowBorderCacheEntry result = super.get(key);

        if (result == null)
        {
            ShadowBorderCacheKey shadowBorderCacheKey = (ShadowBorderCacheKey) key;

            result = new ShadowBorderCacheEntry(shadowBorderCacheKey);
            put(shadowBorderCacheKey, result);
        }

        return result;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected boolean removeEldestEntry(java.util.Map.Entry<ShadowBorderCacheKey, ShadowBorderCacheEntry> eldest)
    {
        return size() > capacity;
    }

}
